package com.ruoyi.basedata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.basedata.domain.DwAreas;
import com.ruoyi.basedata.domain.LouDong;
import com.ruoyi.basedata.domain.Room;
import com.ruoyi.basedata.mapper.DwAreasMapper;
import com.ruoyi.basedata.mapper.LouDongMapper;
import com.ruoyi.basedata.mapper.RoomMapper;
import com.ruoyi.basedata.service.ILouDongService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SnowflakeUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 楼栋Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-09-07
 */
@Service
@Slf4j
public class LouDongServiceImpl implements ILouDongService 
{
    @Autowired
    private LouDongMapper louDongMapper;

    @Autowired
    private DwAreasMapper areasMapper;

    @Autowired
    private RoomMapper roomMapper;

    /**
     * 查询楼栋
     * 
     * @param ID 楼栋主键
     * @return 楼栋
     */
    @Override
    public LouDong selectLouDongByID(Long ID)
    {
        return louDongMapper.selectLouDongByID(ID);
    }

    /**
     * 查询楼栋列表
     * 
     * @param louDong 楼栋
     * @return 楼栋
     */
    @Override
    public List<LouDong> selectLouDongList(LouDong louDong)
    {
        return louDongMapper.selectLouDongList(louDong);
    }

    /**
     * 新增楼栋
     * 
     * @param louDong 楼栋
     * @return 结果
     */
    @Override
    public int insertLouDong(LouDong louDong)
    {

        List<LouDong> louDongList = louDongMapper.selectList(new LambdaQueryWrapper<LouDong>()
                .eq(LouDong::getAreaCode, louDong.getAreaCode())
                .eq(LouDong::getLdName, louDong.getLdName()));
        if (null != louDongList && louDongList.size() > 0){
            return 0;
        }
        SnowflakeUtils snowflakeUtils = new SnowflakeUtils(0,0);
        String id = String.valueOf(snowflakeUtils.nextId());
        louDong.setCreateTime(DateUtils.getNowDate());
        louDong.setDeleteMark(0);
        louDong.setLdId("ld"+id);
        return louDongMapper.insertLouDong(louDong);
    }

    /**
     * 修改楼栋
     * 
     * @param louDong 楼栋
     * @return 结果
     */
    @Override
    public int updateLouDong(LouDong louDong)
    {
        return louDongMapper.updateLouDong(louDong);
    }

    /**
     * 批量删除楼栋
     * 
     * @param IDs 需要删除的楼栋主键
     * @return 结果
     */
    @Override
    public int deleteLouDongByIDs(Long[] IDs)
    {
        List<LouDong> louDongList = louDongMapper.selectBatchIds(Arrays.asList(IDs));
        List<Long> deleteFailList  = new ArrayList<>();
        List<Long> deleteList = new ArrayList<>();
        louDongList.forEach(louDong ->{
            List<Room> rooms = roomMapper.selectList(new LambdaQueryWrapper<Room>()
                    .eq(louDong.getLdId() != null, Room::getLdId, louDong.getLdId()));
            if (rooms.size() > 0){
                deleteFailList.add(louDong.getID());
            }else {
                deleteList.add(louDong.getID());
            }
        });
        if (deleteList.size() == 0){
            return 0;
        }else {
            return louDongMapper.deleteBatchIds(deleteList);
        }

    }

    /**
     * 删除楼栋信息
     * 
     * @param ID 楼栋主键
     * @return 结果
     */
    @Override
    public int deleteLouDongByID(Long ID)
    {
        return louDongMapper.deleteById(ID);
    }

    @Override
    public List<LouDong> selectListByAreaId(Long areaId) {
        DwAreas dwAreas = areasMapper.selectById(areaId);
        return louDongMapper.selectListByAreaCode(dwAreas.getAreaCode());
    }

    @Override
    public List<LouDong> selectListByAreaCode(String areaCode) {
        return louDongMapper.selectList(new LambdaQueryWrapper<LouDong>()
                .eq(areaCode!=null,LouDong::getAreaCode,areaCode));
    }

    @Override
    public String importData(List<LouDong> list, boolean updateSupport, String operName) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入楼栋数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (LouDong louDong : list)
        {
            try {
                List<LouDong> louDongList = louDongMapper.selectList(new LambdaQueryWrapper<LouDong>()
                        .eq(LouDong::getAreaCode, louDong.getAreaCode())
                        .eq(LouDong::getLdName, louDong.getLdName()));
                if (null != louDongList && louDongList.size() > 0){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、楼栋名称 " + louDong.getLdName() + "该区域下有相同名称的楼栋");
                }else {
                    SnowflakeUtils snowflakeUtils = new SnowflakeUtils(0,0);
                    String id = String.valueOf(snowflakeUtils.nextId());
                    louDong.setCreateTime(DateUtils.getNowDate());
                    louDong.setDeleteMark(0);
                    louDong.setLdId("ld"+id);
                    louDongMapper.insertLouDong(louDong);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、楼栋名称 " + louDong.getLdName() + " 导入成功");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、楼栋名称 " + louDong.getLdName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
